package cn.manjuu.touhou.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.manjuu.touhou.db.ToHoDBOpenHelper;
import cn.manjuu.touhou.domain.BaseInfo;

public class BaseInfoDao {

	ToHoDBOpenHelper helper = null;
	private static final String TABLE = "base_info";
	private static final String _ID = "_id";
	private static final String NICK_NAME = "nick_name";
	private static final String MONEY = "money";

	public BaseInfoDao(Context context) {
		super();
		this.helper = ToHoDBOpenHelper.getInstance(context);
	}

	public long insert(BaseInfo baseInfo) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(NICK_NAME, baseInfo.getNickName());
		values.put(MONEY, baseInfo.getMoney());
		long id = db.insert(TABLE, null, values);
		db.close();
		return id;
	}

	public int delete(int _id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		int delete = db.delete(TABLE, _ID + "=?", new String[] { "" + _id });
		return delete;
	}

	public int update(BaseInfo baseInfo) {
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(NICK_NAME, baseInfo.getNickName());
		values.put(MONEY, baseInfo.getMoney());
		int i = db.update(TABLE, values, _ID + "=?",
				new String[] { "" + baseInfo.get_id() });
		db.close();
		return i;
	}

	public BaseInfo query(int _id) {
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor c = db.query(TABLE, null, _ID + "=?", new String[] { "" + _id },
				null, null, null);
		String value = null;
		BaseInfo baseInfo = null;
		if (c.moveToNext()) {
			baseInfo = new BaseInfo();
			baseInfo.set_id(c.getInt(c.getColumnIndex(_ID)));
			baseInfo.setNickName(c.getString(c.getColumnIndex(NICK_NAME)));
			baseInfo.setMoney(c.getLong(c.getColumnIndex(MONEY)));
		}
		c.close();
		db.close();
		return baseInfo;
	}

	public List<BaseInfo> queryAll() {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor c = db.query(TABLE, null, null, null, null, null, null);
		String value = null;
		List<BaseInfo> baseInfos = new ArrayList<BaseInfo>();
		BaseInfo baseInfo = null;
		while (c.moveToNext()) {
			baseInfo = new BaseInfo();
			baseInfo.set_id(c.getInt(c.getColumnIndex(_ID)));
			baseInfo.setNickName(c.getString(c.getColumnIndex(NICK_NAME)));
			baseInfo.setMoney(c.getLong(c.getColumnIndex(MONEY)));
			baseInfos.add(baseInfo);
		}
		c.close();
		db.close();
		return baseInfos;
	}

}
